package com.kotiln.lgc.lib_network.net.callback;


import android.os.Handler;
import android.util.Log;


import androidx.appcompat.app.AppCompatDialog;

import com.kotiln.lgc.lib_network.net.RestCreator;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class RequestCallbacks implements Callback<String> {
    private final IRequest REQUEST;
    private final ISuccess SUCCESS;
    private final IError ERROR;
    private final IFailure FAILURE;
    private final AppCompatDialog DIALOG;

    public RequestCallbacks(IRequest iRequest, ISuccess iSuccess, IError iError, IFailure iFailure, AppCompatDialog dialog) {
        this.REQUEST = iRequest;
        this.SUCCESS = iSuccess;
        this.ERROR = iError;
        this.FAILURE = iFailure;
        this.DIALOG = dialog;
    }

    @Override
    public void onResponse(Call<String> call, Response<String> response) {
        if (response.isSuccessful()) {
            if (call.isExecuted()) {
                if (SUCCESS != null) {
                    SUCCESS.onSuccess(response.body());
                }
            }
        } else {
            if (ERROR != null) {
                ERROR.onError(response.code(), response.message());
            }
        }

        if (REQUEST != null) {
            REQUEST.onRequestEnd();
        }

        onRequestFinish();
    }

    @Override
    public void onFailure(Call<String> call, Throwable throwable) {
        if (FAILURE != null) {
            FAILURE.onFailure();
        }

        if (REQUEST != null) {
            REQUEST.onRequestEnd();
        }

        onRequestFinish();
    }

    private void onRequestFinish() {
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                RestCreator.getParams().clear();
                if (DIALOG != null) {
                    DIALOG.dismiss();
                }
                Log.i("RequetCallbacks", "--------------");
            }
        }, 500);
    }
}
